package org.core.blog.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.core.blog.mapper.ArticleMapper;
import org.core.blog.pojo.Article;
import org.core.blog.pojo.PageQueryParam;
import org.core.blog.pojo.PageResult;
import org.core.blog.pojo.SearchParam;
import org.core.blog.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;

    @Override
    public List<Article> getList() {
        return articleMapper.findAll();
    }

    @Override
    public PageResult<Article> getPage(PageQueryParam pageQueryParam) {
        PageHelper.startPage(pageQueryParam.getPage(), pageQueryParam.getPageSize());
        List<Article> articles=getList();
        Page<Article> pageInfo=(Page<Article>)articles;
        log.info("文章列表：{}",articles);
        int totalPages=(int) Math.ceil((double) pageInfo.getTotal() / pageQueryParam.getPageSize());
        return new PageResult<Article>(pageInfo.getTotal(), totalPages, pageInfo.getResult());
    }

    @Transactional
    @Override
    public void creatArticle(Article article) {
        article.setCreatedAt(LocalDateTime.now());
        article.setUpdatedAt(LocalDateTime.now());
        articleMapper.InsertArticle(article);
        log.info("创建文章：{}",article);
    }

    @Override
    public Article getArticle(Integer id) {
        Article article = articleMapper.selectArticleById(id);
        log.info("获取文章：{}",article);
        return article;
    }

    @Transactional
    @Override
    public void updateArticle(Article article) {
        article.setUpdatedAt(LocalDateTime.now());
        articleMapper.updateById(article);
        log.info("更新文章：{}",article);
    }

    @Override
    public PageResult<Article> searchPage(SearchParam searchParam) {
        PageHelper.startPage(searchParam.getPage(), searchParam.getPageSize());
        List<Article> articles=articleMapper.queryByParam(searchParam);
        Page<Article> pageInfo=(Page<Article>)articles;
        log.info("搜索文章列表：{}",articles);
        int totalPages=(int) Math.ceil((double) pageInfo.getTotal() / searchParam.getPageSize());
        return new PageResult<Article>(pageInfo.getTotal(),totalPages,pageInfo.getResult());
    }

    @Transactional
    @Override
    public void deleteArticle(Integer id) {
        articleMapper.deleteById(id);
        log.info("删除id为{}的文章",id);
    }
}
